import { Component, OnInit } from '@angular/core';
import { InspectionRecordsService } from '../../../../services/project/inspection/inspection-records.service';
import { InspectPropertySettingService } from '../../../../services/project/inspection/inspect-property-setting.service'
import { ActivatedRoute, Router } from '@angular/router';
import { searchModel } from './inspection-records.model';
import { Utils } from 'src/app/common/helper/util-helper';
import * as moment from 'moment-timezone';

@Component({
  selector: 'app-inspection-records',
  templateUrl: './inspection-records.component.html',
  styleUrls: ['./inspection-records.component.scss']
})
export class InspectionRecordsComponent implements OnInit {

  constructor(
    private router: Router,
    private InspectionRecordsService: InspectionRecordsService,
    private routerInfo: ActivatedRoute,
    public inspectPropertySettingService: InspectPropertySettingService,
  ) {
  }

  public searchModel = new searchModel()
  public nzTotal: number = 0;
  public recordList: Array<object> = [];
  public isModalVisible: boolean = false;
  public detailInfo: any = {};
  public nzPageIndex: number = 1;
  public formInfo: any = {
    selectedType: '0',
    selectedStauts: '0',
    startValue: null,
    endValue: null
  };
  public name: string = JSON.parse(window.localStorage.getItem('project')).name;
  public projectId: string;
  public allChecked: boolean = false;// 全选状态
  public indeterminate: boolean = false;// 半选状态
  public checkedDatas: any = [];// 当前选中的数据集合
  public checkOptionsList: any = []; // 检查项下拉列表
  public isviewImg;
  public curl; // 当前点击的图片地址
  public checkindex = []; // 复检列表编号
  public annex = [];
  public annexForVideo = [];
  public annexForImg = [];
  public status = {
    // // 所需项目级权限
    // PIpagePermissions: [
    //   // 查看巡检记录
    //   'APJ.PI.View',

    // ],
    // // 当前页面项目级权限状态
    // PIpageAuthorty: {

    //   PIDrawings: null,

    // }
  };
  routeToSurvey() {
    const projectId = JSON.parse(window.localStorage.getItem('project')).id;
    this.router.navigate([`/inner/project/${projectId}/survey`], {queryParams: { info: 'project' }});
  }

  /**
   * 表格数据
   */
  public async getPageInfo() {
    this.searchModel.projectId = JSON.parse(window.localStorage.getItem('project')).id;
    this.searchModel.checkItemId = this.searchModel.type ? this.searchModel.type.value : '';
    const result = await this.InspectionRecordsService.QueryChecksPagedList(this.searchModel)
    result.result.items.forEach(element => {
      element.notifyUsersArray = JSON.parse(element.notifyUsersArray)
    });
    this.nzTotal = result.result.totalCount
    this.recordList = result.result.items
    console.log(this.recordList)
  }

  public async getDetail(id) {
    const result = await this.InspectionRecordsService.QueryCheckDetailById({ input: id })
    this.detailInfo = result.result
    // 编号
    let index = result.result.checkAndFeedbacksList.length / 2;
    this.checkindex = [];
    // index
    for (let i = 1; i <= index; i++) {
      this.checkindex.push(i)
    }


    // 附件
    this.annex = result.result.attachments;

    this.annex.forEach(element => {
      //  console.log(element.split('.')[element.split('.').length - 1]);
      if (element.split('.')[element.split('.').length - 1] == 'mp4') {
        this.annexForVideo.push(element)
      } else {
        this.annexForImg.push(element)
      }
    });
    this.isModalVisible = true;
  }

  //   public async deleteLot() {
  //   let checkArray = []
  //   this.checkedDatas.forEach(element => {
  //     if (element.checked) {
  //       checkArray.push(element.id)
  //     }
  //   });
  //   const result = await this.InspectionRecordsService.BatchRemoveChecks(checkArray)
  // }

  public async pageChange(index) {
    this.searchModel.skipCount = index - 1;
    await this.getPageInfo();
  }

  /**
 * 表格操作相关
 */
  private refreshCheckboxStatus() {
    let dataList = this.recordList;
    const allChecked = dataList.filter((value: any) => !value['disabled']).every((value: any) => value['checked'] === true);
    const allUnChecked = dataList.filter((value: any) => !value['disabled']).every((value: any) => !value['checked']);

    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);

    // 获取当前选中的数据
    let checkedDatas = [];
    dataList.forEach((data) => {
      if (data['checked']) {
        checkedDatas.push(data);
      }
    });
    this.checkedDatas = checkedDatas;
    console.log(this.checkedDatas)
    // 改变批量操作按钮状态
    // this.delBtnStatus = !dataList.some((value: any) => value['checked']);
  }

  public checkAll(status: any, callBack?: Function): void {
    this.recordList.forEach((data: any) => {
      let eachStatus;
      if (callBack) {
        eachStatus = callBack(data);
      }
      if (eachStatus !== false) {
        data['checked'] = status;
      }
    });
    this.refreshCheckboxStatus();
  }

  // 预览文件
  viewImg(url) {
    this.curl = url;
    this.isviewImg = true;
  }
  // 关闭预览
  Cancel() {
    this.isviewImg = false;

  }
  closemodal() {
    this.isModalVisible = false;
    this.annexForVideo = [];
    this.annexForImg = []
  }



  // 获取检查类型选项

  public async getCheckOptions() {
    // const projectId = this.routerInfo.snapshot.params['projectId'];
    this.projectId = JSON.parse(window.localStorage.getItem('project')).id;
    const params = {
      projectId: this.projectId,
      maxResultCount: 1000,
      skipCount: 0,
      type: 2,
      parentId: '00000000-0000-0000-0000-000000000000'
    }
    const res = await this.inspectPropertySettingService.QueryCheckItems(params)
    console.log(res.result)
    // this.checkOptionsList =[]
    // this.nodesList = this.treeEdit.transformTreeNode(res.result, this.treeAttributes);
    const tempOrg = [];
    res.result.forEach(element => {
      // console.log(element)
      tempOrg.push({ label: element.name, value: element.id });
    });
    this.checkOptionsList = tempOrg;
  }
  

  /**
   * 搜索条件
   * @param date
   */
  onStartChange(date: Date): void {
    if (date) {
      this.formInfo.startValue = moment.tz(date, 'Asia/Chongqing').local().format('YYYY-MM-DD');
      this.searchModel.creationTimeRange[0] = this.formInfo.startValue;
    } else {
      this.searchModel.creationTimeRange.splice(0, 1)
    }
  }

  onEndChange(date: Date): void {
    if (date) {
      this.formInfo.endValue = moment.tz(date, 'Asia/Chongqing').local().format('YYYY-MM-DD');
      this.searchModel.creationTimeRange[1] = this.formInfo.endValue;
    } else {
      this.searchModel.creationTimeRange.splice(1, 1)
    }
  }
  ngOnInit() {
    this.getPageInfo();
    this.getCheckOptions()
  }

}
